package com.itheima.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author itheima
 * @Date 2022/5/6 11:19
 */
@RestControllerAdvice("com.itheima.controller")
public class GlobalExceptionHandler {

    /**
     * 1.捕获：java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'user4' for key 'idx_username'
     * 2.返回数据：失败：{code:0,msg:"错误信息",data:""}
     */
    @ExceptionHandler
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //message==>Duplicate entry 'user4' for key 'idx_username'
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] ss = message.split(" ");
            //需求：如果账号出现重复，捕获异常 ，给出精准提示：“user4”已存在
            return R.error(ss[2] + "已存在");
        }
        return R.error("未知错误！");
    }

    /**
     * 捕获自定义异常CustomerException进行处理，获取抛出的异常信息，返回R.error();
     */
    @ExceptionHandler
    public R<String> customerExceptionHandler(CustomerException ex) {
        //throw new CustomerException("删除的该分类下，关联了其他菜品，不能删除！");\
        //R.error("删除的该分类下，关联了其他菜品，不能删除！")
        return R.error(ex.getMessage());
    }
}
